package com.luo.ai.assistant.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luo.ai.assistant.etl.MyEtlService;
import com.luo.ai.assistant.file.FileDetailService;
import com.luo.ai.assistant.file.MyFileStorageService;
import com.luo.ai.assistant.file.model.FileDetail;
import com.luo.ai.assistant.file.model.FileDetailQuery;
import com.luo.ai.assistant.file.model.FileUploadDto;
import org.dromara.x.file.storage.core.FileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Chat Controller
 *
 * @author luohq
 * @date 2025-01-02
 */
@RestController
@RequestMapping("/ai/etl")
class EtlController {

    private Logger log = LoggerFactory.getLogger(EtlController.class);

    /**
     * ETL服务
     */
    private MyEtlService myEtlService;

    /**
     * 文件存储服务
     */
    private MyFileStorageService myFileStorageService;
    /**
     * 文件数据库记录服务
     */
    private FileDetailService fileDetailService;

    public EtlController(MyEtlService myEtlService, MyFileStorageService myFileStorageService, FileDetailService fileDetailService) {
        this.myEtlService = myEtlService;
        this.myFileStorageService = myFileStorageService;
        this.fileDetailService = fileDetailService;
    }

    /**
     * 上传文件
     *
     * @param fileUploadDto 文件上传DTO
     * @return 是否导入成功
     */
    @PostMapping(value = {"/files/upload"}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public FileInfo uploadFile(FileUploadDto fileUploadDto) {
        Map<String, String> metadataMap = new HashMap<>();
        metadataMap.put("type", fileUploadDto.getType());
        return this.myFileStorageService.uploadFile(fileUploadDto.getFile(), metadataMap);
    }

    /**
     * 分页查询文件
     *
     * @param fileDetailQuery 文件查询条件
     * @return 文件分页
     */
    @GetMapping(value = {"/files"})
    public Page<FileDetail> findPage(FileDetailQuery fileDetailQuery) {
        return this.fileDetailService.findPage(fileDetailQuery);
    }

    /**
     * 删除文件
     *
     * @param fileIds 文件ID
     * @return 是否删除成功
     */
    @DeleteMapping(value = {"/files/{ids}"})
    public Boolean deleteFiles(@PathVariable(name = "ids") List<String> fileIds) {
        this.myFileStorageService.deleteFileByIds(fileIds);
        return true;
    }

    /**
     * 训练文件
     *
     * @param fileIds 文件ID集合
     * @return 是否训练成功
     */
    @PostMapping(value = {"/train/{ids}"})
    public Boolean train(@PathVariable(name = "ids") List<String> fileIds) {
        // 批量训练文件
        this.myEtlService.etlFileBatch(fileIds);
        return true;
    }
}